package gmongo

import (
	"reflect"

	log "gitee.com/abril-cx/gtools/glog"
	utils "gitee.com/abril-cx/gtools/gutils"
	"go.mongodb.org/mongo-driver/bson"
)

func DefaultCreate(data bson.M) {
	data["created"] = utils.GetDateTime(0)
	data["updated"] = utils.GetDateTime(0)
	data["deleted"] = nil
}

func DefaultUpdate(data bson.M) {
	data["updated"] = utils.GetDateTime(0)
}

func DefaultDelete(data bson.M) {
	data["deleted"] = utils.GetDateTime(0)
}

func DefaultModel(fields []bson.M, data bson.M) (bson.M, error) {
	for _, v := range fields {
		field := v["field"].(string)
		types := v["types"].(string)
		if field == "_id" {
			continue
		}
		if _, ok := data[field]; !ok {
			value := v["default"]
			if value == nil {
				data[field] = nil
			} else {
				value := v["default"].(string)
				switch types {
				case "string":
					data[field] = value
				case "int64":
					data[field], _ = utils.StrToInt64(value)
				case "float64":
					data[field], _ = utils.StrToFloat64(value)
				case "bool":
					if value == "true" {
						data[field] = true
					} else {
						data[field] = false
					}
				}
			}
		} else {
			if data[field] == nil {
				continue
			}
			field_type := reflect.TypeOf(data[field]).Name()
			switch field_type {
			case "string":
				if types == "int64" {
					value, err := utils.StrToInt64(data[field].(string))
					if err != nil {
						return data, log.ErrorReturn("类型错误", err.Error(), "int64", data[field])
					}
					data[field] = value
				} else if types == "float64" {
					value, err := utils.StrToFloat64(data[field].(string))
					if err != nil {
						return data, log.ErrorReturn("类型错误", err.Error(), "float64", data[field])
					}
					data[field] = value
				} else if types == "bool" {
					if data[field].(string) == "true" {
						data[field] = true
					} else {
						data[field] = false
					}
				}
			case "int32":
				if types == "int64" {
					data[field] = int64(data[field].(int32))
				}
			case "int":
				if types == "int64" {
					data[field] = int64(data[field].(int))
				}
			case "float64":
				if types == "int64" {
					data[field] = int64(data[field].(float64))
				}
			}
			if types == "object_id" {

			} else {
				if types != reflect.TypeOf(data[field]).Name() {
					return data, log.ErrorReturn("类型错误", "types: "+types, data[field], reflect.TypeOf(data[field]).Name(), field)
				}
			}
		}
	}
	return data, nil
}
